//
//  LLChannelEchoViewController.swift
//  MyEcho
//
//  Created by longlong on 16/1/25.
//  Copyright © 2016年 LongLong. All rights reserved.
//


class LLChannelEchoViewController: UIViewController,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout{

    @IBOutlet var headerView: UIView!
    @IBOutlet weak var buttonNew: UIButton!
    @IBOutlet weak var buttonHot: UIButton!
    @IBOutlet weak var myCollectionView: UICollectionView!
    var  dataArray:NSMutableArray = [] ;
    var  page:NSInteger = 1;

    override func viewDidLoad() {
        super.viewDidLoad()
        headerView.frame = CGRectMake(0, 108,320, 44 )
        myCollectionView.addSubview(headerView)

        
        getDataFromNetWork(self.page, isHot: true) ;
        
        //上拉加载更多
        self.myCollectionView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingBlock: { () -> Void in
            self.getDataFromNetWork(++self.page,isHot:true);
        });

    }
    
    @IBAction func clickNewOrHot(sender: UIButton) {
        buttonNew.setTitleColor(UIColor.grayColor(), forState: UIControlState.Normal);
        buttonHot.setTitleColor(UIColor.grayColor(), forState: UIControlState.Normal);
        sender.setTitleColor(UIColor.redColor(), forState: UIControlState.Normal);
        page=1;
        self.dataArray.removeAllObjects();
        getDataFromNetWork(page, isHot: sender.tag==10002);
    }
    
    func getDataFromNetWork(page:NSInteger,isHot:Bool){
        AFAppDotNetAPIClient.sharedClient().GET(AllDefine.channePageURLWith(page, isHot: isHot) as String, parameters: nil, success: {(task: NSURLSessionDataTask?, JSON: AnyObject?) -> Void in
            if (JSON is NSDictionary){
                let dic =  JSON as? NSDictionary ;
                if (dic?.objectForKey("message")?.isEqual("success") != nil){
                    let ary = dic?.objectForKey("result")?.objectForKey("data") as? NSArray;
                    self.myCollectionView.mj_footer.endRefreshing();
                    for var inDic in ary!{
                        let channel:Channel = Channel();
                        channel.setValuesForKeysWithDictionary(inDic as! [String : AnyObject]);
                        self.dataArray.addObject(channel);
                    }
                    
                    self.myCollectionView.reloadData();
                    print("侧滑中心：获取数据成功");
                    
                }
            }else{
                print("侧滑中心：获取数据失败")
            }
            
            }) { (task: NSURLSessionDataTask?, error: NSError?) -> Void in
                print("获取数据失败:\(error!)");
        }
    }

    //MARK: UICollectionViewDataSource UICollectionViewDelegate
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 2;
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        switch (section){
           case 0:
            return 1;
           default:
            return self.dataArray.count;
        }
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        switch (indexPath.section){
            case 0:
                let cell:ClassificationCell = collectionView.dequeueReusableCellWithReuseIdentifier("ClassificationCell", forIndexPath: indexPath) as! ClassificationCell;
                return cell;
            default:
                let cell:ChannelEchoCell = collectionView.dequeueReusableCellWithReuseIdentifier("ChannelEchoCell", forIndexPath: indexPath) as! ChannelEchoCell;
                let channal:Channel = self.dataArray[indexPath.row] as! Channel;
                cell.cellLabel.text = channal.name as String;
                cell.cellImageView.sd_setImageWithURL(NSURL.init(string: channal.pic_200 as String), placeholderImage: nil);

                return cell;
        }
    }
    
    //点击事件
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let channel:Channel = self.dataArray[indexPath.row] as! Channel;
        GlobalDataObject.sharedInstance.channel = channel;
        let url = "http://echosystem.kibey.com/channel/info?list_order=".stringByAppendingFormat("%@&id=%@&page=", "hot",channel.ID);
        self.mm_drawerController.closeDrawerAnimated(true) { (Bool) -> Void in
            let nav =  self.mm_drawerController.centerViewController as! UINavigationController;
            let viewController = nav.viewControllers[0] as! LLMainViewController;
            viewController.urlHeader = url;
        }
    }
    
    //MARK: UICollectionViewDelegateFlowLayout
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        switch (indexPath.section){
           case 0:
            let width = UIScreen.mainScreen().bounds.size.width*5/6;
            return CGSizeMake(width, 120);
           default:
            let width = UIScreen.mainScreen().bounds.size.width*5/6-20;
            return CGSizeMake(width, 100);

        }
    }
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
        switch (section) {
        case 0:
            return UIEdgeInsetsMake(0, 0, 0, 0);
            
        default:
            return UIEdgeInsetsMake(44, 0, 0, 0);
        }
    }
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
        switch (section) {
        case 0:
            return 0;
        default:
            return 10 ;
        }
    }
}
